import { CartItem } from '@/types/cart'
import { ApiRes } from '@/types/data'
import { Skus } from '@/types/goods'
import request from '@/utils/request'
import { setProfile } from '@/utils/storage'
import { defineStore } from 'pinia'
import useStore from '..'

const useCartStore = defineStore({
  id: 'cart',
  // 数据持久化插件
  persist: {
    key: 'rabbit-cart-92',
  },
  // 状态
  state: () => ({
    // 购物车列表
    list: [] as CartItem[],
  }),
  // 方法
  actions: {
    async addCart(data: CartItem) {
      if (this.isLogin) {
        await request.post('/member/cart', {
          skuId: data.skuId,
          count: data.count,
        })
        this.getCartList()
      } else {
        // 本地添加购物车
        // 1. 判断购物车列表中是否有该商品数据
        const goods = this.list.find((item) => item.skuId === data.skuId)
        if (goods) {
          // 2. 如果商品存在，直接把数量加起来
          goods.count += data.count
        } else {
          // 3. 如果商品不存在，直接添加该商品
          this.list.unshift(data)
        }
        // localStorage.setItem('addCart', JSON.stringify(this.list))
      }
    },
    // 获取购物车列表
    async getCartList() {
      if (this.isLogin) {
        const res = await request.get<ApiRes<CartItem[]>>('/member/cart')
        this.list = res.data.result
      } else {
        // console.log('获取本地购物车')
        // 主动更新储存的商品信息
        this.list.forEach(async (cartItem) => {
          const { skuId } = cartItem
          // 根据 skuId 获取最新商品信息
          const res = await request.get<ApiRes<CartItem>>(
            `/goods/stock/${skuId}`
          )
          // 保存最新商品信息
          const lastCartInfo = res.data.result
          // 更新商品现价
          cartItem.nowPrice = lastCartInfo.nowPrice
          // 更新商品库存
          cartItem.stock = lastCartInfo.stock
          // 更新商品是否有效
          cartItem.isEffective = lastCartInfo.isEffective
        })
      }
    },
    // 删除购物车商品
    async delCart(skuIds: string[]) {
      if (this.isLogin) {
        await request.delete('/member/cart', {
          data: {
            ids: skuIds,
          },
        })
        this.getCartList()
      } else {
        // 本地过滤掉含有skuid的
        this.list = this.list.filter((item) => !skuIds.includes(item.skuId))
      }
    },
    // 更新数据:商品数量、选中状态
    async updateCart(id: string, data: { selected?: boolean; count?: number }) {
      if (this.isLogin) {
        await request.put(`/member/cart/${id}`, data)
        this.getCartList()
      } else {
        // 根据id找到当前sku
        const sku = this.effectiveList.find((item) => item.skuId === id)!
        if (data.selected !== undefined) sku.selected = data.selected //因为selected可为false，所以需要判断是否不等于undefined
        if (data.count !== undefined) sku.count = data.count
      }
    },
    // 修改全选或者全不选
    async updateCartAllSelected(isSelected: boolean) {
      if (this.isLogin) {
        await request.put('/member/cart/selected', {
          selected: isSelected,
        })
        this.getCartList()
      } else {
        this.list.forEach((item) => {
          item.selected = isSelected
        })
      }
    },
    // 更新修改的sku
    async updateCartSku(oldSkuId: string, sku: Skus) {
      /*思路:删除旧的;新增修改后的:分两种情况:原本列表里有,就只增加数量,原本列表里面没有,就给列表新增一项 */
      if (this.isLogin) {
        const oldGoods = this.list.find((item) => item.skuId === oldSkuId)!
        // 删除原来的商品
        await request.delete('/member/cart', {
          data: {
            ids: [oldGoods.skuId],
          },
        })
        // 新增
        await request.post('/member/cart', {
          skuId: sku.id,
          count: oldGoods.count,
        })
        this.getCartList()
      } else {
        // 1. 删除原来的商品
        const oldSku = this.effectiveList.find(
          (item) => item.skuId === oldSkuId
        )!
        this.delCart([oldSkuId])
        // 2. 添加新的商品
        this.addCart({
          ...oldSku,
          skuId: sku.id,
          nowPrice: sku.price,
          price: sku.price,
          stock: sku.inventory,
          attrsText: sku.specs
            .map((item) => item.name + ':' + item.valueName)
            .join(' '),
        })
      }
    },
    // 清空购物车
    clearCart() {
      // 退出登录需清空购物车
      this.list = []
    },

    // 合并购物车
    async mergeLocalCart() {
      const data = this.list.map(({ skuId, selected, count }) => ({
        skuId,
        selected,
        count,
      }))
      await request.post('/member/cart/merge', data)
      // 合并成功，重新获取购物车列表
      this.getCartList()
    },
  },
  // 计算
  getters: {
    // 筛选出有库存且有效的商品
    effectiveList(): CartItem[] {
      return this.list.filter((item) => item.stock > 0 && item.isEffective)
    },
    // 总件数
    totalCount(): number {
      return this.effectiveList.reduce((sum, item) => sum + item.count, 0)
    },
    // 总价格
    totalPrice(): string {
      return this.effectiveList
        .reduce((sum, item) => sum + item.count * Number(item.nowPrice), 0)
        .toFixed(2)
    },
    // 选中的商品列表
    selectedList(): CartItem[] {
      return this.effectiveList.filter((item) => item.selected)
    },
    selectedCounts(): number {
      return this.selectedList.reduce((total, item) => total + item.count, 0)
    },
    selectedPrice(): string {
      return this.selectedList
        .reduce((sum, item) => sum + item.count * Number(item.nowPrice), 0)
        .toFixed(2)
    },
    // 单选全选
    isAllchecked(): boolean {
      return this.effectiveList.every((item) => item.selected)
    },
    // 查看是否为登录状态
    isLogin(): boolean {
      const { user } = useStore()
      // return Boolean(user.profile.token) 或者下面的!!方式,可以将string类型转换成boolean类型
      return !!user.profile.token
    },
  },
})
export default useCartStore
